package com.bw.house.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.bw.house.config.GuliESConfig;
import org.apache.commons.lang3.StringUtils;
import org.apache.lucene.search.TotalHits;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.MatchAllQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bw.common.utils.PageUtils;
import com.bw.common.utils.Query;

import com.bw.house.dao.HouseRentDao;
import com.bw.house.entity.HouseRentEntity;
import com.bw.house.service.HouseRentService;


@Service("houseRentService")
public class HouseRentServiceImpl extends ServiceImpl<HouseRentDao, HouseRentEntity> implements HouseRentService {

    @Autowired
    private HouseRentDao houseRentDao;

    @SuppressWarnings("all")
    @Autowired
    private RestHighLevelClient client;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<HouseRentEntity> wrapper = new QueryWrapper<>();
        String s = (String) params.get("key");
        if(StringUtils.isNotEmpty(s)) {
        wrapper.like("house_title",s);
        }
        IPage<HouseRentEntity> page = this.page(
                new Query<HouseRentEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils slist(Map<String, Object> params) {
        try {
        SearchRequest searchRequest = new SearchRequest("house");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //新建布尔查询
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        //进行查询
        String title = (String) params.get("title");
        String limit1 = (String) params.get("limit");
        String page1 = (String) params.get("page");
        Integer limit = Integer.parseInt(limit1);
        Integer page = Integer.parseInt(page1);
        if(!title.equals("")) {
            QueryBuilders.matchQuery("houser_title",title);
        }

        //分页
        searchSourceBuilder.from((page-1)* limit);
        searchSourceBuilder.size(limit);
        //高亮
        HighlightBuilder namehight = new HighlightBuilder().field("houser_title");
        namehight.preTags("<span style='color:red;'>");
        namehight.postTags("</span>");
        searchSourceBuilder.highlighter(namehight);

        searchSourceBuilder.query(boolQueryBuilder);
        searchRequest.source(searchSourceBuilder);
        //执行查询
         SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
        //处理高亮
         SearchHits hits = searchResponse.getHits();
            TotalHits totalHits = hits.getTotalHits();
// the total number of hits, must be interpreted in the context of totalHits.relation
            long numHits = totalHits.value;
// whether the number of hits is accurate (EQUAL_TO) or a lower bound of the total (GREATER_THAN_OR_EQUAL_TO)
            TotalHits.Relation relation = totalHits.relation;
            float maxScore = hits.getMaxScore();
            SearchHit[] searchHits = hits.getHits();
            ArrayList<HouseRentEntity> list = new ArrayList<>();
            for (SearchHit hit : searchHits) {
                // do something with the SearchHit
                String index = hit.getIndex();
                String id = hit.getId();
                float score = hit.getScore();
                String sourceAsString = hit.getSourceAsString();
                HouseRentEntity houseRentEntity = JSON.parseObject(sourceAsString, new TypeReference<HouseRentEntity>() {
                });
                houseRentEntity.setHouseId(Integer.parseInt(id));

                Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                HighlightField highlight = highlightFields.get("house_title");
                if(highlight!=null) {
                    Text[] fragments = highlight.fragments();
                    String fragmentString = fragments[0].string();
//                resultVO.setHouseName(fragmentString);
                }
                list.add(houseRentEntity);
            }
            int size = list.size();
            //List<?> list, int totalCount, int pageSize, int currPage
            return new PageUtils(list,size,limit,page);
        } catch (IOException e) {
            e.printStackTrace();
        }

    return null;
    }

    @Scheduled(cron = "* 0/2 * * * *")
    public void runner() {
        try {
            List<HouseRentEntity> list = baseMapper.selectList(null);
            BulkRequest bulkRequest = new BulkRequest();
            for(HouseRentEntity houseRentEntity : list){
                IndexRequest indexRequest = new IndexRequest("house");
                indexRequest.id(houseRentEntity.getHouseId().toString());
                String jsonString = JSONObject.toJSONString(houseRentEntity);
                indexRequest.source(jsonString, XContentType.JSON);
                bulkRequest.add(indexRequest);
            }
            BulkResponse bulk = client.bulk(bulkRequest, GuliESConfig.COMMON_OPTIONS);
            System.out.println("同步数据"+new Date());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}